<script lang="ts" setup>
import { useVbenModal } from '@vben/common-ui';
import { cloneDeep } from '@vben/utils';

import { useVbenForm } from '#/adapter/form';

const groupIndex = ref<number>();
const groupAttributes = ref<any[]>([]);
const groupType = ref('');
const [Form, formApi] = useVbenForm({
  handleSubmit: onSubmit,
  schema: [
    {
      component: 'Input',
      defaultValue: '',
      componentProps: {
        placeholder: '请输入',
      },
      dependencies: {
        show: false,
        triggerFields: ['id'],
      },
      fieldName: 'id',
      label: 'ID',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'name',
      label: '分组名称',
      rules: 'required',
    },
    {
      component: 'Select',
      defaultValue: groupType.value,

      componentProps: {
        class: 'w-full',
        disabled: true,
        options: [
          {
            value: 'parameter',
            label: '参数分组',
          },
          {
            value: 'spec',
            label: '规格分组',
          },
        ],
      },
      fieldName: 'type',
      label: '分组类型',
      rules: 'required',
    },
    {
      component: 'Switch',
      defaultValue: 1,
      componentProps: {
        class: '',
        checkedValue: 1,
        unCheckedValue: 0,
        checkedChildren: '启用',
        unCheckedChildren: '停用',
      },
      fieldName: 'status',
      label: '状态',
    },
  ],
  layout: 'vertical',
  showDefaultActions: false,
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
    labelClass: 'w-2/6',
  },
});

const [GroupModal, GroupModalApi] = useVbenModal({
  fullscreenButton: false,
  onConfirm: async () => {
    await formApi.validateAndSubmitForm();
  },
  onOpenChange(isOpen) {
    if (!isOpen) return;
    const modalData = GroupModalApi.getData();
    groupAttributes.value = modalData?.group?.attributes ?? [];
    groupType.value = modalData.group_type;
    formApi.setFieldValue('type', modalData.group_type);
    groupIndex.value = modalData?.group_index ?? -1;
    if (modalData?.group) {
      formApi.setValues(modalData.group);
    }
  },
});

async function onSubmit(values: any) {
  values.attributes = groupAttributes.value;
  if (values?.id) {
    values.update = true;
  }
  GroupModalApi.setData({
    values: cloneDeep(values),
    group_index: groupIndex.value,
    isUpdata: true,
  });
  GroupModalApi.close();
}
</script>
<template>
  <GroupModal>
    <Form />
  </GroupModal>
</template>

<style lang="scss" scoped></style>
